package com.allen.control;

import com.allen.bean.Goods;
import com.allen.service.GoodsService;
import com.allen.service.StockService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/goodsCtrl")
public class GoodsControl extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        String parm = req.getParameter("parm");
        switch (parm) {
            case "list":
                list(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "toEdit":
                toEdit(req, resp);
                break;
            case "edit":
                edit(req, resp);
                break;
            case "delete":
                delete(req, resp);
                break;
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer gid = Integer.parseInt(req.getParameter("gid"));
        new GoodsService().delete(gid);
        resp.sendRedirect("/erp/goodsCtrl?parm=list");
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        new GoodsService().update(req, resp);
        resp.sendRedirect("/erp/goodsCtrl?parm=list");
    }

    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer gid = Integer.parseInt(req.getParameter("gid"));
        Goods goods = new GoodsService().findById(gid);
        req.setAttribute("goods", goods);
        req.getRequestDispatcher("/goods/edit.jsp").forward(req, resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer id = new GoodsService().add(req, resp);
        new StockService().add (id);
        resp.sendRedirect("/erp/goodsCtrl?parm=list");
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Goods> goodses = new GoodsService().getAll();
        req.setAttribute("goodses", goodses);
        req.getRequestDispatcher("/goods/list.jsp").forward(req, resp);
    }
}

